package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 服务器端
 */
public class Server {
    private ServerSocket serverSocket;
    private ExecutorService threadPool= Executors.newFixedThreadPool(50);
    //private List<PrintWriter> allOut=new ArrayList<>();
    private Map<String, PrintWriter> allOut = new HashMap<>();

    public Server() {
        try {
            System.out.println("正在启动服务器");
            serverSocket = new ServerSocket(8848);
            System.out.println("服务器启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接了");
                Runnable handler = new ClientHandler(socket);
                threadPool.execute(handler);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private String host;
        private String nickname;

        public ClientHandler(Socket socket) {
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }

        public void run() {
            PrintWriter pw = null;
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                nickname = br.readLine();

                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw, true);
                synchronized (allOut) {//抢谁锁谁，要对同一个集合操作，那就锁集合
                    allOut.put(nickname, pw);
                }
                broadcast(nickname + "[" + host + "]" + "上线了，当前在线人数:" + allOut.size());

                String message;
                while ((message = br.readLine()) != null) {
                    if (message.startsWith("@")) {
                        sendMessageToSomeone(message);
                    } else {
                        broadcast(nickname + "[" + host + "]" + "说:" + message);
                        saveMessage(nickname,null,message);
                    }
                }
            } catch (IOException e) {
            } finally {
                synchronized (allOut) {
                    //allOut.remove(pw);
                    allOut.remove(nickname);
                }
                broadcast(nickname + "[" + host + "]" + "下线了，当前在线人数:" + allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void broadcast(String message) {
            System.out.println(message);
            synchronized (allOut) {
                /*for (PrintWriter o : allOut) {
                    o.println(message);
                }
                 */
                for (PrintWriter o : allOut.values()) {
                    o.println(message);
                }
            }
        }

        private void sendMessageToSomeone(String message) {
            if (message.matches("@.+:.+")) {
                String toNickName = message.substring(1, message.indexOf(":"));
                if (allOut.containsKey(toNickName)) {
                    PrintWriter pw = allOut.get(toNickName);
                    String toMessage = message.substring(message.indexOf(":") + 1);
                    pw.println(nickname + "悄悄对你说:" + toMessage);
                    saveMessage(nickname,toNickName,toMessage);
                } else {
                    PrintWriter pw=allOut.get(nickname);
                    pw.println("该用户不存在");
                }
            } else {
                PrintWriter pw = allOut.get(nickname);
                pw.println("私聊格式不正确，格式应当为 @对方昵称:私聊消息");
            }
        }
        private void saveMessage(String fromUser,String toUser,String message){
            try(
                    Connection connection=DBUtil.getConnection()
            ) {
                String sql="INSERT INTO chatinfo(from_user,to_user,content) " +
                           "VALUES(?,?,?)";
                PreparedStatement ps=connection.prepareStatement(sql);
                ps.setString(1,fromUser);
                ps.setString(2,toUser);
                ps.setString(3,message);
                ps.executeUpdate();

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}